package handler

import (
	"encoding/json"
	"note-master/cache"
	"note-master/moder"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
)

func Add(c *gin.Context) {
	title := c.PostForm("title")
	username := c.PostForm("username")
	password := c.PostForm("password")

	if title == "" || username == "" || password == "" {
		c.JSON(200, gin.H{
			"mas":  "不能为空",
			"code": 500,
		})
		return
	}
	data := moder.User{
		Title:    title,
		Username: username,
		Password: password,
	}
	err := moder.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"mas":  "发布失败",
			"code": 500,
		})
		return
	}

	redis_key := "article_" + strconv.Itoa(int(data.ID))
	var article moder.User
	jsonData, _ := json.Marshal(article)
	cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	c.JSON(200, gin.H{
		"mas":  "发布成功",
		"code": 200,
	})
	return

}

func Del(c *gin.Context) {
	id := c.PostForm("id")
	var data moder.User
	err := moder.DB.Where("id=?", id).Delete(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"mas":  "删除失败",
			"code": 500,
		})
		return
	}

	redis_key := "redis_del" + id
	cache.Rdb.Del(cache.Ctx, redis_key)
	c.JSON(200, gin.H{
		"mas":  "删除成功",
		"code": 500,
	})
	return
}

func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "2"))
	offset := (page - 1) * size
	/*

	 */
	var user []moder.User
	redis_key := "redis_list" + strconv.Itoa(page)
	result, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if result == "" {
		moder.DB.Offset(offset).Limit(size).Order("id asc").Find(&user)
		jsonData, _ := json.Marshal(user)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(result), &user)
	}

	var total int64

	moder.DB.Model(&moder.User{}).Count(&total)
	c.JSON(200, gin.H{
		"mas":   "成功",
		"code":  200,
		"data":  user,
		"total": total,
	})
	return

}

func Detail(c *gin.Context) {
	id := c.Query("id")
	var user moder.User
	redis_key := "redis_detail" + id
	result, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if result == "" {
		moder.DB.Where("id=?", id).First(&user)
		jsonData, _ := json.Marshal(user)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(result), &user)
	}

	c.JSON(200, gin.H{
		"mas":  "成功",
		"code": 200,
		"data": user,
	})
	return
}
